#ifndef __STORE_APP_H__
#define __STORE_APP_H__

#include <stdio.h>
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/sem.h>
#include <sys/shm.h> 
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define N 4
#define LEDPATH "/dev/myled"

int ledfd;
char led_buf[2];

pthread_t tid; 
key_t key;

/*共享内存ID*/
int shmid;
/*信号灯集ID*/
int semid;
/*消息队列 ID*/
int msqid;

/*承接用户阈值设置变量*/
int set_tmp_up;
int set_tmp_dow;
int set_hum_up;
int set_hum_dow;
int set_illu_up;
int set_illu_dow;

/*读取环境数据变量*/
int env_tmp;
int env_hum;
int env_illu;
int env_led;
int env_fan;
int env_beep;


/*进程间同步 P/V操作*/
union semun{ 
	int val; 
	struct semid_ds *buf; 
	unsigned short *array; 
	struct seminfo *__buf; 
};


void p(int semid,int sem_sum){ 
	struct sembuf sem; 
	sem.sem_num = sem_sum; 
	sem.sem_op = -1; 	//ｐ操作 
	sem.sem_flg = 0; 
	semop(semid,&sem,1); 
}

void v (int semid,int sem_sum){ 
	struct sembuf sem; 
	sem.sem_num = sem_sum; 
	sem.sem_op = 1; 	//V操作 
	sem.sem_flg = 0; 
	semop(semid,&sem,1); 
}

/*登录结构*/
typedef struct login{
	char name[20];
	char password[7];
	int flags;//记录登录成功与否
} login_t;

/*设备控制结构*/
typedef struct dev_ctrl{
	int led;
	int fan;
	int beep;
} dev_ctrl_t;

/*环境设置结构 用于承接网页下发阈值*/
typedef struct env_set{
	int tmp_up;
	int tmp_dow;
	int hum_up;
	int hum_dow;
	int illu_up;
	int illu_dow;
} env_set_t;

/*环境数据结构 用于向网页发送环境状态*/
typedef struct env_state{
	int tmp;
	int hum;
	int illu;
	int led;
	int fan;
	int beep;
} env_state_t;

/*整体消息结构*/
typedef struct msgbuf { 
	long mtype;
	unsigned int store_num; 
	login_t log_msg;
	env_state_t env_state_msg;
	env_set_t env_set_msg;
	dev_ctrl_t dev_ctrl_msg;
}msg_t;

/*整体消息结构 变量 用于传输网页上传下发的数据*/
msg_t msg;
msg_t login_msg;
msg_t view_msg;
msg_t set_msg;
msg_t ctrl_msg;

/*承接共享内存地址*/
msg_t *shm_addr;

/*线程同步信号量*/
sem_t msg_sem;		//消息处理线程
sem_t login_sem; 	//登录线程
sem_t env_view_sem; //查看环境线程
sem_t env_set_sem; 	//设置环境线程
sem_t dev_ctrl_sem; //控制设备线程

/*消息处理线程*/
void *msg_thread(void *p);

/*登录处理线程*/
void *login_thread(void *p);

/*查看环境处理线程*/
void *env_view_thread(void *q);

/*设置阈值处理线程*/
void *env_set_thread(void *p);

/*控制设备处理线程*/
void *dev_ctrl_thread(void *p);

/*线程初始化*/
int thread_init(void);

/*共享内存初始化*/
int shm_init(void);

/*消息队列初始化*/
int msgqueue_init(void);

/*系统初始化*/
int sys_init(void);


#endif
